import { _decorator, Component, math, Node, Vec3 } from 'cc';
import { PathEvent } from '../PlayableFramework/Tools/Path/PathEvent';

const { ccclass, property } = _decorator;

@ccclass('PathEvent_Rotate')
export class PathEvent_Rotate extends PathEvent {

    public override addEvent() {
        console.log("重新执行添加事件" + this.pathMove);
        if (this.pathMove != null) {
            console.log("添加事件");
            // 处理路径开始事件
            this.pathMove.onPathStart = (index , allPathPoints) => {
                this.flipIfNeeded(this.target.worldPosition, allPathPoints[0]);
            };

            // 添加路径点完成事件
            for (let i = 0; i < this.pathMove.getPathPoints().length; i++) {
                this.pathMove.addPointCompleteEvent(i, (index , allPathPoints) => {
                    if (index + 1 >= allPathPoints.length) return; // 如果没有下一个点，则不做处理

                    this.flipIfNeeded(allPathPoints[index], allPathPoints[index + 1]);
                });
            }
        }
    }

    /**
     * 根据下一个路径点的位置，判断是否需要翻转目标物体
     * @param currentPoint - 当前路径点
     * @param nextPoint - 下一个路径点
     */
    private flipIfNeeded(from:Vec3,to:Vec3) {

        let direction = to.clone().subtract(from);
        direction = direction.normalize();

        this.target.children[0].children[0].setRotationFromEuler(0, -math.toDegree(Math.atan2(direction.z, direction.x)), 0);
    }
}
